<?php

/*
 * litchicms
 * Copyright (C) 2010-5-1 Author: tiefa(539247@qq.com)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
!defined('BRK') && exit("!");

/**
 * 文件标识函数
 */
function main() {

}

/**
 * 获取数据系列函数，之 brk_get_get
 * @param  $string
 * @return $array
 */
function brkget_get($string) {


    return array(1, 2, 3, 4);
}

/**
 * 插入数据函数
 * @param str $tablename
 * @param array $data
 *
 */
function brk_insert($tablename, $dataarr, $RETURN_AUTO_INCREMENT=TRUE) {
    if ($tablename == '') {
        return FALSE;
    }
    $tablename = $GLOBALS['BRK_CONF']['prefix'] . $tablename;

    $fields = '';
    $values = '';

    foreach ($dataarr as $k => $v) {
        $fields.=$k . ",";
        $values.="'" . $v . "',";
    }

    $fields = substr($fields, 0, -1);
    $values = substr($values, 0, -1);


    $sql = "INSERT INTO " . $tablename . "(" . $fields . ") VALUES(" . $values . ");";

    if ($rs = $GLOBALS['Db']->query($sql)) {
        if ($RETURN_AUTO_INCREMENT)
            $rs = $GLOBALS['Db']->insert_id();
        brk_log("6", " OK!" . $sql);
    }else {
        brk_log("0", " DIE!" . $sql);
    }

    return $rs;
}

/**
 * 执行SQL语句
 * @param str
 *
 */
function brk_query($sql) {
    $sql = str_replace("!'", $GLOBALS['BRK_CONF']['prefix'], $sql);
    brk_log("6", " brk_query!" . $sql);

    if ($rs = $GLOBALS['Db']->query($sql)) {
        return $rs;
    } else {
        return FALSE;
    }
}

/**
 * 更新数据函数
 * @param str $tablename
 * @param array $data
 *
 */
function brk_update($tablename, $dataarr, $argstr) {
    if ($tablename == '') {
        return FALSE;
    }
    $tablename = $GLOBALS['BRK_CONF']['prefix'] . $tablename;

    $setstr = '';

    foreach ($dataarr as $k => $v) {
        $setstr.= " " . $k . "='" . $v . "',";
    }
    $setstr = substr($setstr, 0, -1);

    $sql = "UPDATE " . $tablename . " SET " . $setstr . " " . $argstr;

    if ($rs = $GLOBALS['Db']->query($sql)) {
        brk_log("6", " OK!" . $sql);
    } else {
        brk_log("0", " DIE!" . $sql);
        return FALSE;
    }

    return $rs;
}

/**
 * 删除数据函数
 * @param str $tablename
 * @param array $data
 *
 */
function brk_delete($tablename, $argstr="") {
    $tablename = $GLOBALS['BRK_CONF']['prefix'] . $tablename;
    if (trim($argstr) == '') {
        return FALSE;
    } else {
        $sql = "DELETE FROM " . $tablename . "  " . $argstr;
        if ($rs = $GLOBALS['Db']->query($sql)) {
            brk_log("6", " OK!" . $sql);
        } else {
            brk_log("0", " DIE!" . $sql);
            return FALSE;
        }
        return $rs;
    }
    return FALSE;
}

/**
 * 查询数据函数
 * @param str $tablename
 * @param str $sql
 *
 */
function brk_select($tablename, $fieldstr="*", $argstr='', $DISTINCT=FALSE) {
    $tablename = $GLOBALS['BRK_CONF']['prefix'] . $tablename;
    $sql = "SELECT " . ($DISTINCT ? 'DISTINCT' : '') . " " . $fieldstr . " FROM " . $tablename . " " . $argstr;
    if ($rs = $GLOBALS['Db']->query($sql)) {
        brk_log("6", " OK!" . $sql);
    } else {
        brk_log("0", " DIE!" . $sql);
        return FALSE;
    }
    return $rs;
}

/**
 * 关连查询
 * 
 */
function brk_select_join($tables, $fields, $argstr, $DISTINCT=FALSE) {
    if (!is_array($tables = explode(",", $tables)))
        return FALSE;
    $mainTable = $tables[0];
    foreach ($tables as $k => $v) {
        $fields = str_replace('{' . $k . '}', $GLOBALS['BRK_CONF']['prefix'] . $v, $fields);
        $argstr = str_replace('{' . $k . '}', $GLOBALS['BRK_CONF']['prefix'] . $v, $argstr);
    }
    return brk_select($mainTable, $fields, $argstr, $DISTINCT);
}

/**
 * 查询单挑数据函数
 * @param str $tablename
 * @param str $sql
 *
 */
function brk_select_one($tablename='', $fieldstr="*", $argstr='') {
    if ($rs = brk_select($tablename, $fieldstr, $argstr))
        return $GLOBALS['Db']->fetch_array($rs);
    else
        return FALSE;
}

/**
 * 查询符合某条件的总数
 * @param str $tablename
 * @param str $sql
 *
 */
function brk_select_num($tablename='', $argstr='') {
    if ($rs = brk_select($tablename, "COUNT(*)", $argstr)) {
        $row = $GLOBALS['Db']->fetch_row($rs);
        return $row[0];
    }
    else
        return FALSE;
}

/**
 * 用户登录
 * @param $user_login string 登录名
 * @param $user_pass  string 已加密的密码
 * @param $session    bool   是否session用户名
 * @return bool 成功true 失败false
 */
function brk_login($user_login, $user_pass, $session=TRUE) {
    global $BRK_GLOBAL;
    $row = brk_select_one('users', "*", " WHERE user_login='" . $user_login . "' AND user_pass='" . $user_pass . "'");
    if ($row) {
        $data = array(
            'user_lastloginip' => $GLOBALS['BRK_GLOBAL']['ip'],
            'user_lastlogintime' => date("Y-m-d H:i:s", $GLOBALS['BRK_GLOBAL']['datearray'][0]),
        );
        //dump(true);
        require SYSTEM . 'data/group_rigths/' . $row['group_id'] . '.php';

        unset($_SESSION['brk_verifycode']);
        brk_update('users', $data, " WHERE user_login='" . $user_login . "'");
        $session && $_SESSION['brk_login'] = $row;
        $GLOBALS['BRK_USER'] = &$_SESSION['brk_login'];
        return TRUE;
    } else {
        return FALSE;
    }
}

/*
 * 权限读取
 */

function brk_right_get($id, $type) {
    if (empty($id) || empty($type))
        exit("哎呀呀,brk_right_get");
    if (key_exists($id, $GLOBALS['BRK_GLOBAL']['RIGTHS'][$type])) {
        return $GLOBALS['BRK_GLOBAL']['RIGTHS'][$type][$id];
    } else {
        check_rights_by_id($id);
    }
}

function brk_right_get_node($id) {
    return brk_right_get($id, 'node');
}

function brk_right_get_note($id) {
    return brk_right_get($id, 'note');
}

function brk_right_get_parent($id) {
    return brk_right_get($id, 'parent');
}

function brk_right_get_parents($id) {
//    while ($this->parent[$id] != -1) {
//        $id = $parent[$this->layer[$id]] = $this->parent[$id];
//    }
//    ksort($parent);
//    reset($parent);
//    return $parent;
}

function brk_right_get_child($id = 0) {
    if (array_key_exists($id, $GLOBALS['BRK_GLOBAL']['RIGTHS']['child'])) {
        return $GLOBALS['BRK_GLOBAL']['RIGTHS']['child'][$id];
    } else {
        return array();
    }
}

/*
 * 链接数据库
 */

function openSQL($type="mysql", $pconnect=0) {
    global $BRK_CONF;
    if (file_exists(SYSTEM . 'include/driver/' . $type . '/class.php')) {
        require SYSTEM . 'include/driver/' . $type . '/class.php';
        $Db = new mysql($BRK_CONF['dbhost'], $BRK_CONF['dbuser'], $BRK_CONF['dbpw'], $BRK_CONF['prefix'], $BRK_CONF['dbname'], $pconnect, $BRK_CONF['dbcharset']);
        return $Db;
    }
}

/*
 * 载入表操作函数 
 */

function openSQLTF($type="mysql") {
    global $BRK_CONF;
    if (file_exists(SYSTEM . 'include/driver/' . $type . '/table.php')) {
        require SYSTEM . 'include/driver/' . $type . '/table.php';
    }
}

/**
 * 替换数据中的\和" 为\\和\"
 */
function replace_yy($data) {
    return str_replace(array("\\", "\""), array("\\\\", "\\\""), $data);
}

/**
 * 简单的数组转换成JSON 只有对象...
 */
function array_to_json($arr) {
    exit("检查此函数");
    $string = "{";

    $i = 0;
    $c = count($arr);
    foreach ($arr as $k => $v) {
        $string.=$k . ":";

        $temp = '';
        is_numeric($v) && $temp = $v;
        is_array($v) && $temp = array_to_json($v);
        is_string($v) && $temp = "\"" . replace_yy($v) . "\"";
        is_bool($v) && $temp = ($v ? "true" : "false");

        $i++;

        if ($i != $c) {
            $temp.=",";
        }

//        $temp.="\n";
        $string.=$temp;
    }

    $string.="}";

    return $string;
}

/**
 * 变量转成能够写入文件 并且被PHP引入的字符串 主要用于数组
 */
function var2string($var) {
    exit("检查此函数");
    if (is_numeric($var)) {
        return $var;
    }
    if (is_string($var)) {
        return "\"" . replace_yy($var) . "\"";
    }
    if (is_bool($var)) {
        return $var ? "TRUE" : "FALSE";
    }
    if (is_null($var)) {
        return "null";
    }
    if (is_array($var)) {
        $temp = "array(";
//        $temp = "array(\n";

        $i = 1;
        $count = count($var);
        foreach ($var as $key => $value) {
            $temp.=var2string($key) . "=>" . var2string($value) . ($i == $count ? '' : ',');
//            $temp.=var2string($key) . "=>" . var2string($value) . ($i == $count ? '' : ',') . "\n";

            $i++;
        }
        $temp.=")";
//        $temp.="\n)";
        return $temp;
    }


    return "?????";
}

/*
 * 常用时间转换为时间戳 Y-m-d H:i:s
 */

function totimestamp($strtime) {
    $array = explode("-", $strtime);
    if (count($array) != 3) {
        return FALSE;
    }
    $year = $array[0];
    $month = $array[1];

    $array = explode(":", $array[2]);
    if (count($array) != 3) {
        return FALSE;
    }
    $minute = $array[1];
    $second = $array[2];

    $array = explode(" ", $array[0]);
    if (count($array) != 2) {
        return FALSE;
    }
    $day = $array[0];
    $hour = $array[1];

    if (!checkdate($month, $day, $year)) {
        return FALSE;
    }

    return mktime($hour, $minute, $second, $month, $day, $year);
}

//JSON
if (!function_exists('json_encode')) {

    function json_encode($a=false) {
        if (is_null($a))
            return 'null';
        if ($a === false)
            return 'false';
        if ($a === true)
            return 'true';
        if (is_scalar($a)) {
            if (is_float($a)) {
                // Always use "." for floats.
                return floatval(str_replace(",", ".", strval($a)));
            }

            if (is_string($a)) {
                static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
                return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
            }
            else
                return $a;
        }
        $isList = true;
        for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
            if (key($a) !== $i) {
                $isList = false;
                break;
            }
        }
        $result = array();
        if ($isList) {
            foreach ($a as $v)
                $result[] = json_encode($v);
            return '[' . join(',', $result) . ']';
        } else {
            foreach ($a as $k => $v)
                $result[] = json_encode($k) . ':' . json_encode($v);
            return '{' . join(',', $result) . '}';
        }
    }

}

/**
 * 截取
 */
function brk_substr($str, $length, $start=0) {
    return $str;
}

/**
 * 获取数据集信息
 */
function _get_all_collections() {
    global $BRK_GLOBAL, $Db;
    if (empty($BRK_GLOBAL['collections'])) {
        $BRK_GLOBAL['collections'] = array();
        $rs = brk_select('collection');
        while ($row = $Db->fetch_array($rs)) {
            $BRK_GLOBAL['collections'][$row['collection_id']] = $row;
            $BRK_GLOBAL['collections'][$row['collection_ename']] = &$BRK_GLOBAL['collections'][$row['collection_id']];
        }
    }
}

/*
 * 组装URL的前面部分.可能需要查别名表
 */

function _build_url_pre($param=array()) {
    if (empty($_GET['m']) && empty($_GET['part'])) {
        return "";
    }
    if (in_array($temp = "m-" . $param['channel'], $GLOBALS['BRK_GLOBAL']['alias'])) {
        $URL = $GLOBALS['BRK_CONF']['rootdir'] . '/' . array_search($temp, $GLOBALS['BRK_GLOBAL']['alias']);
        if (strpos($URL, "?") === FALSE) {
            $URL.="?";
        }
    } else {
        $URL = $GLOBALS['BRK_CONF']['rootdir'] . "/index.php?$temp-";
    }
    if ($_GET['m'] != $param['collection_ename']) {
        $URL.= 'part-' . $param['collection_ename'] . '-';
    }

    return $URL;
}

/*
 * 获取某数据集的分类数据
 *
 * 这里面有点别扭,在全局变量中用了数据集ID来保存他的分类信息..
 */

function _get_collection_category($collection_id) {
    global $BRK_GLOBAL;
    empty($BRK_GLOBAL['category']) && $BRK_GLOBAL['category'] = $BRK_GLOBAL['category_index'] = array();
    if (empty($BRK_GLOBAL['category'][$collection_id])) {
        //是主类 引文件
        if (is_file($file = SYSTEM . 'cache/category/coll_' . $collection_id . '.php')) {
            require $file;
            $BRK_GLOBAL['category'][$collection_id] = array($CATEGORY_ROOT, $cids, $relationships);
            //做反向索引.方便有可能调用的子类
            foreach ($cids as $value) {
                $BRK_GLOBAL['category_index'][$value] = $collection_id;
            }
            $CATEGORY = &$BRK_GLOBAL['category'][$collection_id];
        }
        //是子类
        else if ($temp = $BRK_GLOBAL['category_index'][$collection_id]) {
            $CATEGORY = &$BRK_GLOBAL['category'][$temp];
        }
        //不是人
        else {
            msg(array("分类有误", 't'));
        }

        return $CATEGORY;
    } else {
        return $BRK_GLOBAL['category'][$collection_id];
    }
}

/**
 * 获取数据集 列表型
 */
//($data|COLL_list:array('fields'=>'id',cid'=>分类id,'sub'=>是否包含子类,'sort'=>'排序方式','num'=>条数,'channel'=>'目标频道')
function COLL_list($param=array()) {
    global $BRK_GLOBAL, $Db, $RT;
    if (empty($BRK_GLOBAL['COLL_list'])) {
        $BRK_GLOBAL['COLL_list'] = array();
    }

    (empty($param['partid']) || ($param['partid'] = intval($param['partid'])) == 0 ) && msg(array("数据集id有误", 't'));

    if (!empty($BRK_GLOBAL['COLL_list'][$param['partid']])) {
        return $BRK_GLOBAL['COLL_list'][$param['partid']];
    }

    _get_all_collections();
    empty($BRK_GLOBAL['collections'][$param['partid']]) && msg(array("模板出错,找不到该数据集", 't'));

    $coll = &$BRK_GLOBAL['collections'][$param['partid']];

    if (!$coll['collection_status']) {
        msg(array('数据集 ' . $param['partid'] . '# 不存在或者服务已关闭', 't'));
    }

    empty($param['isbg']) && $param['isbg'] = FALSE;
    empty($param['fields']) && $param['fields'] = "*";
    empty($param['sort']) && $param['sort'] = "top DESC, sort DESC";
    empty($param['num']) && $param['num'] = 10;
    empty($param['cid']) && $param['cid'] = 0;
    empty($param['sub']) && $param['sub'] = 0;

//    empty($param['channel']) && $param['channel'] = $BRK_GLOBAL['collections'][$param['id']]['collection_ename'];
    empty($param['channel']) && $param['channel'] = $RT['v']['m'];

    //分页
    //page
    if (!empty($param['pageid']) && $param['pageid'] != "$") {
        if (preg_match('/\W/', $param['pageid']) === FALSE) {
            exit("分页标识不合法");
        }
    }


    $param['num'] = intval($param['num']);
    $param['cid'] = intval($param['cid']);


    $URL = _build_url_pre(array('channel' => $param['channel'], 'collection_ename' => $coll['collection_ename']));


    $LIMIT = " LIMIT " . $param['num'];

    $re_arr = array();

    if (empty($param['cid'])) {
        if (!empty($param['pageid'])) {
            $allnums = current(brk_select_one("_coll_" . $coll['collection_ename'], 'count(id) as num', "WHERE status=1"));
            $page_info = COLL_PAGE_info($param['pageid'], $param['num'], $allnums, $param['isbg']);
            $LIMIT = " LIMIT " . ($page_info['current'] - 1) * $page_info['oenPageNum'] . "," . $page_info['oenPageNum'];
        }
        $rs = brk_select(
                        "_coll_" . $coll['collection_ename'],
                        $param['fields'],
                        "WHERE status=1  ORDER BY " . $param['sort'] . $LIMIT
        );
        while ($row = $Db->fetch_array($rs)) {
            if (empty($row['url'])) {
                $row['url'] = $URL . "id-" . $row['id'];
            }
            $re_arr[] = $row;
        }
    } else {
        if ($param['sub']) {
            $CATEGORY = _get_collection_category($param['partid']);
            $thiscategory = $CATEGORY[0][$CATEGORY[2][$param['cid']]];

            if (!empty($param['pageid'])) {
                $num = brk_select_join(
                                "_coll_" . $coll['collection_ename'] . ",ccc_relationships,category",
                                "count(DISTINCT {0}.id)",
                                "INNER JOIN {1} ON {0}.id={1}.id
                                 INNER JOIN {2} ON {1}.cid={2}.cid
                                 WHERE {0}.status=1
                                AND {1}.collection_id =" . $coll['collection_id'] . "
                                AND {2}.lid>=" . $thiscategory['lid'] . "
                                AND {2}.rid<=" . $thiscategory['rid']);
                $allnums = current($Db->fetch_array($num));
                $page_info = COLL_PAGE_info($param['pageid'], $param['num'], $allnums, $param['isbg']);
                $LIMIT = " LIMIT " . ($page_info['current'] - 1) * $page_info['oenPageNum'] . "," . $page_info['oenPageNum'];
            }

            $rs = brk_select_join(
                            "_coll_" . $coll['collection_ename'] . ",ccc_relationships,category",
                            "{0}.*",
                            "INNER JOIN {1} ON {0}.id={1}.id
                             INNER JOIN {2} ON {1}.cid={2}.cid
                             WHERE {0}.status=1
                             AND {1}.collection_id =" . $coll['collection_id'] . "
                             AND {2}.lid>=" . $thiscategory['lid'] . "
                             AND {2}.rid<=" . $thiscategory['rid'] . "
                             ORDER BY {0}.top DESC,{0}.sort DESC,{0}.id DESC $LIMIT", TRUE);
        } else {
            if (!empty($param['pageid'])) {
                $num = brk_select_join(
                                "_coll_" . $coll['collection_ename'] . ",ccc_relationships",
                                "count({0}.id)",
                                "INNER JOIN {1} ON {0}.id={1}.id
                                WHERE {0}.status=1 
                                AND {1}.collection_id =" . $coll['collection_id'] . "
                                AND  {1}.cid=" . $param['cid']);
                $allnums = current($Db->fetch_array($num));
                $page_info = COLL_PAGE_info($param['pageid'], $param['num'], $allnums, $param['isbg']);
                $LIMIT = " LIMIT " . ($page_info['current'] - 1) * $page_info['oenPageNum'] . "," . $page_info['oenPageNum'];
            }
            $rs = brk_select_join(
                            "_coll_" . $coll['collection_ename'] . ",ccc_relationships",
                            "{0}.*",
                            "INNER JOIN {1} ON {0}.id={1}.id
                             WHERE {0}.status=1
                             AND {1}.collection_id =" . $coll['collection_id'] . "
                             AND  {1}.cid=" . $param['cid'] . "
                             ORDER BY {0}.top DESC,{0}.sort DESC,{0}.id DESC $LIMIT");
        }
        while ($row = $Db->fetch_array($rs)) {
            if (empty($row['url'])) {
                $row['url'] = $URL . "category-" . $param['cid'] . "-id-" . $row['id'];
                if (!empty($row['category_cache'])) {
                    $temp = unserialize($row['category_cache']);
                    $row['category'] = $temp;
                }
                $row['category_url'] = "";
                $row['category_img'] = "";
            }
            $re_arr[] = $row;
        }
    }

    $BRK_GLOBAL['COLL_list'][$param['partid']] = $re_arr;

    return $re_arr;
}

/**
 * 获取列表的单条详细数据
 */
function COLL_data($param=array()) {
    global $Db, $GET, $BRK_GLOBAL;

    if (empty($BRK_GLOBAL['COLL_data'])) {
        $BRK_GLOBAL['COLL_data'] = array();
    }

    empty($param['fields']) && $param['fields'] = "*";
    empty($param['partid']) && $param['partid'] = $GET['part'];
    empty($param['id']) && $param['id'] = $GET['id'];

    $param['id'] = intval($param['id']);
    $param['id'] == 0 && msg(array("数据不存在", 't'));

    if (!empty($BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['id']])) {
        return $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['id']];
    }


    _get_all_collections();

    empty($BRK_GLOBAL['collections'][$param['partid']]) && msg(array("找不到该数据集", 't'));

    $coll = $BRK_GLOBAL['collections'][$param['partid']];
    if (!$coll['collection_status']) {
        msg(array('数据集 ' . $param['partid'] . '# 不存在或者服务已关闭', 't'));
    }
    $rs = brk_select_one("_coll_" . $coll['collection_ename'], $param['fields'], "WHERE status=1 AND id=" . $param['id']);
    if ($rs) {
        $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['id']] = $rs;
        return $rs;
    } else {
        msg(array("数据不存在", 't'));
    }
}

/**
 * 获取数据集分类 列表
 */
function COLL_c_list($param=array()) {
    global $Db, $GET, $BRK_GLOBAL;
    if (empty($BRK_GLOBAL['COLL_c_list'])) {
        $BRK_GLOBAL['COLL_c_list'] = array();
    }

    (empty($param['cid']) || ($param['cid'] = intval($param['cid'])) == 0 ) && msg(array("分类id有误", 't'));
    _get_all_collections();
    empty($BRK_GLOBAL['collections'][$param['partid']]) && msg(array("找不到该数据集", 't'));

    empty($param['channel']) && $param['channel'] = $GET['m'];
    empty($param['tree']) && $param['tree'] = FALSE; //树
    empty($param['deep']) && $param['deep'] = 3;     //树 深度
    empty($param['top']) && $param['top'] = FALSE;   //树 去掉最上层那个分类?

    if (!$param['tree']) {
        if (!empty($BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid']])) {
            return $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid']];
        }
    } else {
        if (!empty($BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid'] . '_tree'])) {
            return $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid'] . '_tree'];
        }
    }

    $URL = _build_url_pre(array('channel' => $param['channel'], 'collection_ename' => $BRK_GLOBAL['collections'][$param['partid']]['collection_ename']));

//    $URL = _build_url_pre(array('channel' => $param['channel'])) . $BRK_GLOBAL['collections'][$param['id']]['collection_ename'] . '-';

    $CATEGORY = _get_collection_category($param['partid']);

    $categoryrs = array();

    if ($param['tree']) {



        $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid'] . '_tree'] = $categoryrs;
    } else {
        if (empty($CATEGORY[0][$CATEGORY[2][$param['cid']]])) {
            msg(array('分类id有误', 't'));
        }
        $thiscategory = $CATEGORY[0][$CATEGORY[2][$param['cid']]];
        $clayer = $thiscategory['clayer'] + 1;
        $lid = $thiscategory['lid'];
        $rid = $thiscategory['rid'];

        foreach ($CATEGORY[0] as $cat) {
            if (($cat['clayer'] == $clayer) && ($cat['lid'] > $lid) && ($cat['rid'] < $rid)) {
                $cat['url'] = $URL . 'category-' . $cat['cid'];
                $categoryrs[] = $cat;
            }
        }

        $BRK_GLOBAL['COLL_data'][$param['partid'] . '_' . $param['cid']] = $categoryrs;
    }
    return $categoryrs;
}

/**
 * 获取数据集分类 单个分类信息
 */
function COLL_c_data($param=array()) {
    global $Db, $GET, $BRK_GLOBAL;

    if (!empty($param['partid'])) {
        $param['part_id'] = $param['partid'];
    }
    if (!empty($param['partname'])) {
        $param['part_id'] = $param['partname'];
    }

    if (empty($BRK_GLOBAL['COLL_c_data'])) {
        $BRK_GLOBAL['COLL_c_data'] = array();
    }

    (empty($param['cid']) || ($param['cid'] = intval($param['cid'])) == 0 ) && msg(array("分类id有误", 't'));

    _get_all_collections();
    empty($BRK_GLOBAL['collections'][$param['part_id']]) && msg(array("找不到该数据集,请传入正确的partid或partname", 't'));

    if (!empty($BRK_GLOBAL['COLL_c_data'][$param['cid']])) {
        return $BRK_GLOBAL['COLL_c_data'][$param['cid']];
    }

    $CATEGORY = _get_collection_category($BRK_GLOBAL['collections'][$param['part_id']]['collection_id']);

    $BRK_GLOBAL['COLL_c_data'][$param['cid']] = $CATEGORY[0][$CATEGORY[2][$param['cid']]];

    return $BRK_GLOBAL['COLL_c_data'][$param['cid']];
}

/**
 * 获取数据集 简单
 */
function COLL_simple($id, $page=1) {
    global $BRK_GLOBAL;
    if (empty($BRK_GLOBAL['COLL_simple'])) {
        $BRK_GLOBAL['COLL_simple'] = array();
    }
    if (!empty($BRK_GLOBAL['COLL_simple'][$id])) {
        return $BRK_GLOBAL['COLL_simple'][$id];
    }

    global $Db;
    $Coll = brk_select_one('collection', "*", 'WHERE collection_id=' . intval($id) . ' AND collection_status=1');
    if (!$Coll) {
        msg(array('数据集 ' . $id . '# 不存在或者服务已关闭', 't'));
    }

    $rs = brk_select('simple_collection', "*", "WHERE collection_id=" . intval($id));
    $COLLECTION_DATA = array();
    while ($row = $Db->fetch_array($rs)) {
        if ($row['data_type'] == 'array') {
            if (empty($row['collection_value']))
                $row['collection_value'] = array();
            else
                $row['collection_value'] = unserialize($row['collection_value']);
        }
        $COLLECTION_DATA[$row['collection_key']] = $row['collection_value'];
    }
    $BRK_GLOBAL['COLL_simple']['$id'] = $COLLECTION_DATA;
    return $COLLECTION_DATA;
}

/*
 * 获取翻页那个啥
 */

//($page|COLL_PAGE:{
////'pageid'=>'a' //$
//'Previous' => "<a href=\"_URL_\">上一页</a>",
// 'PageNumber' => "<a href=\"_URL_\">\{PageNumber\}</a>",
// 'Next' => "<a href=\"_URL_\">下一页</a>",
// 'Start' => "<a href=\"_URL_\">\{Start\}..</a>",
// 'End' => "<a href=\"_URL_\">..\{End\}</a>",
// 'Current' => "<a href=\"#\" class='current'>\{Current\}</a>"
// 'Input'=>"&nbsp;<input type='text' class='page_div_input' id='page_input_num' value='\{page_input_num\}'/>条/页&nbsp;第<input type='text' class='page_div_input' id='page_input_page' value='\{page_input_page\}'/>页&nbsp;<input class='page_div_button' type='button' id value='GO'/>"
//})
//{$page}
//array(5) {
//  ["input"] => int(1)
//  ["oenPageNum"] => int(10)
//  ["current"] => int(1)
//  ["num"] => string(2) "22"
//  ["pageCount"] => float(3)
//}
function COLL_PAGE($arr, $isbg=FALSE) {
    global $_PAGE, $BRK_GLOBAL;

    if (empty($_PAGE)) {
        return "没有分页信息";
    }
    !key_exists($arr['pageid'], $_PAGE) && $arr['pageid'] = "$";

    $page_info = &$_PAGE[$arr['pageid']];
    $page_var = $page_info['page_var'];
    $pagen_var = $page_info['pagen_var'];

    if ($isbg) {
        $preUrl = preg_replace(array("/\/$page_var-\d*/", "/\/$pagen_var-\d*/"), array("", ""), $BRK_GLOBAL['REQUEST_URI_OLD']);
        $page_var = "/" . $page_var . "-";
        $pagen_var = "/" . $pagen_var . "-";
    } else {
        $preUrl = preg_replace(array("/-$page_var-\d*/", "/-$pagen_var-\d*/"), array("", ""), $BRK_GLOBAL['REQUEST_URI_OLD']);
        $page_var = "-" . $page_var . "-";
        $pagen_var = "-" . $pagen_var . "-";
    }

    $restr = "";
    if (empty($page_info)) {
        return $restr;
    }

    //显示多少个按钮
    $button = 5;
    if ($button > $page_info['pageCount']) {
        $button = $page_info['pageCount'];
    }

    $mid = ceil($button / 2);
    $start = $page_info['current'] - $mid + 1;
    $end = $start + $button - 1;
    if ($start < $mid - 1) {
        $start = 1;
        $end = $start + $button - 1;
    } elseif ($end > $page_info['pageCount']) {
        $start = $page_info['pageCount'] - $button + 1;
        $end = $page_info['pageCount'];
    }

    if ($isbg) {
        //最前面?
        if ($start > 1) {
            $restr.=str_replace(array('{Start}', '_URL_'), array(1, $preUrl . $page_var . 1 . $pagen_var . $page_info['oenPageNum']), $arr['Start']);
            $restr.=str_replace('_URL_', $preUrl . $page_var . ($page_info['current'] - 1) . $pagen_var . $page_info['oenPageNum'], $arr['Previous']);
        }

        for ($index = $start; $index <= $end; $index++) {
            if ($index == $page_info['current']) {
                $restr.=str_replace(array('{PageNumber}', '_URL_'), array($index, $preUrl . $page_var . $index . $pagen_var . $page_info['oenPageNum']), $arr['Current']);
            } else {
                $restr.=str_replace(array('{PageNumber}', '_URL_'), array($index, $preUrl . $page_var . $index . $pagen_var . $page_info['oenPageNum']), $arr['PageNumber']);
            }
        }

        //最后面?
        if ($end < $page_info['pageCount']) {
            $restr.=str_replace('_URL_', $preUrl . $page_var . ($page_info['current'] + 1) . $pagen_var . $page_info['oenPageNum'], $arr['Next']);
            $restr.=str_replace(array('{End}', '_URL_'), array($page_info['pageCount'], $preUrl . $page_var . $page_info['pageCount'] . $pagen_var . $page_info['oenPageNum']), $arr['End']);
        }
    } else {
        //最前面?
        if ($start > 1) {
            $restr.=str_replace(array('{Start}', '_URL_'), array(1, $preUrl), $arr['Start']);
            $restr.=str_replace('_URL_', $preUrl . $page_var . ($page_info['current'] - 1), $arr['Previous']);
        }
        for ($index = $start; $index <= $end; $index++) {
            if ($index == $page_info['current']) {
                $restr.=str_replace(array('{PageNumber}', '_URL_'), array($index, $preUrl . $page_var . $index), $arr['Current']);
            } elseif ($index == 1) {
                $restr.=str_replace(array('{PageNumber}', '_URL_'), array($index, $preUrl), $arr['PageNumber']);
            } else {
                $restr.=str_replace(array('{PageNumber}', '_URL_'), array($index, $preUrl . $page_var . $index), $arr['PageNumber']);
            }
        }
        //最后面?
        if ($end < $page_info['pageCount']) {
            $restr.=str_replace('_URL_', $preUrl . $page_var . ($page_info['current'] + 1), $arr['Next']);
            $restr.=str_replace(array('{End}', '_URL_'), array($page_info['pageCount'], $preUrl . $page_var . $page_info['pageCount']), $arr['End']);
        }
    }


    if (!empty($arr['Input'])) {
        $restr.=str_replace(array("{page_input_num}", "{page_input_page}", "{pageid}"), array($page_info['oenPageNum'], $page_info['current'], $arr['pageid']), $arr['Input']);
    }

    return $restr;
}

function COLL_PAGE_info($pageid, $num=10, $allnums, $isbg=FALSE) {
    $RT_v = &$GLOBALS['RT']['v'];
    $page_info = array();
    $page_var = 'page' . $pageid;
    $pagen_var = 'pagen' . $pageid;
    //输入页数
    if (empty($RT_v[$page_var]) || (($page_info['input'] = intval($RT_v[$page_var])) && $page_info['input'] < 1)) {
        $page_info['input'] = 1;
    }
    //一页显示条数 后台可用
    $page_info['oenPageNum'] = $num;
    if ($isbg && !empty($RT_v['pagen']) && ($temp = intval($RT_v['pagen'])) && $temp > 0) {
        $page_info['oenPageNum'] = $temp;
    }
    //计算出的当前页数
    $page_info['current'] = 1;
    //记录总条数
    $page_info['num'] = 0;
    //记录总页数
    $page_info['pageCount'] = 0;
    $page_info['num'] = $allnums ? $allnums : 0;
    $page_info['pageCount'] = ceil($page_info['num'] / $page_info['oenPageNum']);
    $page_info['current'] = $page_info['pageCount'] < $page_info['input'] ? $page_info['pageCount'] : $page_info['input'];
    $page_info['current'] < 1 && $page_info['current'] = 1;
    $page_info['page_var'] = $page_var;
    $page_info['pagen_var'] = $pagen_var;

    if (empty($GLOBALS['_PAGE'])) {
        $GLOBALS['_PAGE'] = array();
    }

    $GLOBALS['_PAGE'][$pageid] = $page_info;

    return $page_info;
}

/*
 * 获取图片集
 */

//($data|COLL_pic_list:array('fields'=>'id',cid'=>分类id,'sub'=>是否包含子类,'sort'=>'排序方式','num'=>条数,'channel'=>'目标频道')
function COLL_pic_list($param=array()) {
    //需要传入 文章id和数据集id  根据这2个去查
    global $BRK_GLOBAL, $Db, $RT;
    if (empty($BRK_GLOBAL['COLL_pic_list'])) {
        $BRK_GLOBAL['COLL_pic_list'] = array();
    }

    (empty($param['partid']) || ($param['partid'] = intval($param['partid'])) == 0 ) && msg(array("数据集id有误", 't'));

    _get_all_collections();
    empty($BRK_GLOBAL['collections'][$param['partid']]) && msg(array("模板出错,找不到该数据集", 't'));
    $coll = &$BRK_GLOBAL['collections'][$param['partid']];
    empty($param['channel']) && $param['channel'] = $RT['v']['m'];
    $URL = _build_url_pre(array('channel' => $param['channel'], 'collection_ename' => $coll['collection_ename']));

    if (!$coll['collection_status']) {
        msg(array('数据集 ' . $param['id'] . '# 不存在或者服务已关闭', 't'));
    }

    $param['id'] = empty($param['id']) ? (empty($_GET['id']) ? 0 : intval($_GET['id'])) : intval($param['id']);

    if (array_key_exists($param['partid'] . '_' . $param['id'], $BRK_GLOBAL['COLL_pic_list'])) {
        return $BRK_GLOBAL['COLL_pic_list'][$param['partid'] . '_' . $param['id']];
    }

    if ($param['id'] == 0) {
        $rs = brk_select_one("_coll_" . $coll['collection_ename'], "id", "ORDER BY top DESC, sort DESC LIMIT 1");
        if ($rs) {
            $param['id'] = $rs['id'];
        }
        if ($param['id'] == 0) {
            $BRK_GLOBAL['COLL_pic_list'][$param['partid'] . '_' . $param['id']] = array();
            return array();
        }
    }

    $_data = COLL_data(array('id' => $param['id'], 'partid' => $param['partid']));
    if (!$_data) {
        $BRK_GLOBAL['COLL_pic_list'][$param['partid'] . '_' . $param['id']] = array();
        return array();
    }
    $rs = brk_select_join('photos,photo_coll,attachment', '{0}.*,{1}.photo_coll_desc,{2}.*',
                    "INNER JOIN {2} ON {0}.attach_id={2}.attach_id
             INNER JOIN {1} ON {1}.photo_coll_id={0}.photo_coll_id
             WHERE {0}.photo_coll_id=" . $_data['photo_coll_id'] . "
             ORDER BY {0}.photo_sort DESC");

    $_pics = array();
    while ($row = $Db->fetch_array($rs)) {
        $row['url'] = $URL . 'action-show-pic-' . $row['photo_id'] . "-id-" . $param['id'];
        $_pics[] = $row;
    }
    $BRK_GLOBAL['COLL_pic_list'][$param['partid'] . '_' . $param['id']] = $_pics;
    return $_pics;
}